package 笔试.面试手撕;

/**
 * @author:谢君臣
 * @Date:2021/9/3-10:06
 * @version:1.0
 * @function:
 */
public class 单例练习 {
    public static void main(String[] args) {
        A a = new A().getSingleInstance();


        for (int i = 0; i < 4; i++) {
            B b = new B();
            B singleInstance = b.getSingleInstance();
            System.out.println(singleInstance);
        }
        for (int i = 0; i < 4; i++) {
            C c = new C();
            C single = c.getSingleInstance();
            System.out.println(single);
        }

        for (int i = 0; i < 4; i++) {
            D d = new D();
            new Thread(()->{
                System.out.println(d.getSingleInstance());
            }).start();
        }
        new Thread().start(); // group[]
        new Thread().run(); //Runnable.run()

        for (int i = 0; i < 4; i++) {
            E_single single = E_single.SINGLE;
            E instance = single.getInstance();
            instance.test();
            System.out.println(instance);
        }



    }
}
class A{
    private static A instance = new A();
    public A getSingleInstance(){
        return instance;
    }
}
class B{
    private static B instance;

    public B getSingleInstance(){
        if (instance==null){
            synchronized (B.class){
                if (instance ==null) instance = new B();
            }
        }
        return instance;
    }
}
class C{
    private static final C instance = new C();

    public C getSingleInstance(){
        return instance;
    }
}
class D{
    private static volatile D instance;

    public D getSingleInstance(){
        while (instance==null){
            instance = new D();
        }
        return instance;
    }
}
class E{
    public void test(){
        System.out.println("aaa");
    }
}
enum E_single{
    SINGLE;
    private E instance;

    E_single() {
        instance = new E();
    }

    public E getInstance() {
        return instance;
    }
    public void setInstance(E instance) {
        this.instance = instance;
    }
}
